package it.nard.listener;

import java.awt.Color;
import java.util.HashMap;
import java.util.regex.Pattern;

import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;

import org.jdesktop.swingx.JXTable;
import org.jdesktop.swingx.decorator.SearchPredicate;
import org.jdesktop.swingx.decorator.ShadingColorHighlighter;
import org.jdesktop.swingx.search.TableSearchable;

public class TableDocumentListener implements DocumentListener{

	private HashMap<Document, TableListenerBean> tableDocuments = new HashMap<Document, TableListenerBean>();
	
	public void addTableListener (JTextField tField , JXTable table){
		TableListenerBean tlb = new TableListenerBean();
		 tlb.tField = tField;
		 tlb.table  = table;
		 tlb.shadingColorHighlighter= new ShadingColorHighlighter(new SearchPredicate( Pattern.compile("default")));
		 tlb.shadingColorHighlighter.setBackground(Color.GREEN);
		 tlb.table.addHighlighter(tlb.shadingColorHighlighter);
		 tlb.tt = new TableSearchable(table);
		 tlb.table.setSearchable(tlb.tt);
		 tField.getDocument().addDocumentListener(this);
		 tableDocuments.put(tField.getDocument(), tlb);
	}
	
	
	public void insertUpdate(DocumentEvent e) {
		// TODO Auto-generated method stub
		if(e!=null && e.getDocument()!=null)
			search(this.tableDocuments.get(e.getDocument()));
		
		
	}

	public void removeUpdate(DocumentEvent e) {
		// TODO Auto-generated method stub
		if(e!=null && e.getDocument()!=null)
			search(this.tableDocuments.get(e.getDocument()));
	}

	public void changedUpdate(DocumentEvent e) {
		// TODO Auto-generated method stub
		
	}

	private void search(TableListenerBean tlb){
	try{
			tlb.tField.setBackground(Color.WHITE);
		String s = tlb.tField.getText();
		if (s.length() <= 0) {
			return;
		}
		Pattern pattern = Pattern.compile(".*"+s+".*");    
		 SearchPredicate sp = new SearchPredicate(pattern);
		        
		 
		 tlb.shadingColorHighlighter.setHighlightPredicate(sp);
		 
		
		 
		 if(tlb.tt.search(pattern)==-1){
			 tlb.tField.setBackground(Color.red);
		 }
	}catch(Exception e ){
//		e.printStackTrace();
	}
	}
	
}

class TableListenerBean {
	
	 JTextField tField;
	 JXTable table;
	 ShadingColorHighlighter shadingColorHighlighter;
	 TableSearchable tt;
	
}
